import { useUserStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'

// createRouter 创建路由实例，===> new VueRouter()
// 1. history模式: createWebHistory()   http://xxx/user
// 2. hash模式: createWebHashHistory()  http://xxx/#/user

// vite 的配置 import.meta.env.BASE_URL 是路由的基准地址，默认是 ’/‘
// https://vitejs.dev/guide/build.html#public-base-path

// 如果将来你部署的域名路径是：http://xxx/my-path/user
// vite.config.ts  添加配置  base: my-path，路由这就会加上 my-path 前缀了

// console.log(import.meta.env)

/**
 * @description 配置统一路由
 */
const router = createRouter({
  // 统一的路径前缀
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/login', component: () => import('@/views/login/LoginPage.vue')},
    { path: '/',
      component: () => import('@/views/layout/LayoutContainer.vue'),
      redirect: '/article/manage',
      children: [
        { path: '/article/manage', component: () => import('@/views/article/ArticleManage.vue')},
        { path: '/article/channel', component: () => import('@/views/article/ArticleChannel.vue')},
        { path: '/user/profile', component: () => import('@/views/user/UserProfile.vue')},
        { path: '/user/avatar', component: () => import('@/views/user/UserAvatar.vue')},
        { path: '/user/password', component: () => import('@/views/user/UserPassword.vue')}
      ]
    },
  ]
})

// 配置导航守卫
// 与Vue2区别: undefined || true ==> 放行
router.beforeEach((to) => {
  // useUserStore是导入的方法!不是TM的对象！！
  const userStore = useUserStore()
  if (!userStore.token && to.path !== '/login') return '/login'
})


export default router
